import Character from '../base/character';
import DataBus from '../databus';
import { SCREEN_WIDTH, SCREEN_HEIGHT } from '../render';

const databus = new DataBus();

const ALLY_WIDTH = 48;  // 队友宽度
const ALLY_HEIGHT = 64; // 队友高度

// 队友类型
const ALLY_TYPE = {
  WARRIOR: 1,
  ARCHER: 2
};

// 队友行为模式
const BEHAVIOR = {
  FOLLOW: 1,    // 跟随玩家
  DEFEND: 2,    // 防御模式
  ATTACK: 3     // 攻击模式
};

export default class Ally extends Character {
  constructor(allyType) {
    const imgSrc = 'pics/lion.png'; // 统一使用玩家图片
    super(imgSrc, ALLY_WIDTH, ALLY_HEIGHT, ALLY_WIDTH);

    this.allyType = allyType;
    this.behavior = BEHAVIOR.FOLLOW;
    
    // 根据类型设置基础属性
    if (allyType === ALLY_TYPE.WARRIOR) {
      this.maxHp = 150;
      this.baseAttack = 15;
      this.baseDefense = 10;
      this.baseSpeed = 3;
    } else {
      this.maxHp = 100;
      this.baseAttack = 25;
      this.baseDefense = 5;
      this.baseSpeed = 4;
    }
    
    // 属性修饰符
    this.attackModifier = 1.0;  // 攻击力修饰符
    this.defenseModifier = 1.0; // 防御力修饰符
    this.speedModifier = 1.0;   // 速度修饰符
    
    this.hp = this.maxHp;
    this.attackRange = allyType === ALLY_TYPE.WARRIOR ? 60 : 120;
    this.attackInterval = allyType === ALLY_TYPE.WARRIOR ? 45 : 60;
    
    // 初始化位置
    this.x = Math.random() * (SCREEN_WIDTH - ALLY_WIDTH);
    this.y = Math.random() * (SCREEN_HEIGHT - ALLY_HEIGHT);
    
    console.log(`Ally initialized at: ${this.x}, ${this.y}`);
  }

  // 更新队友行为
  update() {
    super.update();
    
    // 自动判断行为模式：优先攻击，其次跟随
    const hasEnemies = databus.enemies && 
                      databus.enemies.some(e => !e.isDying && this.getDistanceTo(e) < 300);
    
    if (hasEnemies) {
      this.behavior = BEHAVIOR.ATTACK;
      this.attackEnemies();
      
      // 向敌人移动
      const nearestEnemy = this.findNearestEnemy();
      if (nearestEnemy) {
        const dx = nearestEnemy.x - this.x;
        const dy = nearestEnemy.y - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance > this.attackRange) {
          const moveX = (dx / distance) * this.speed;
          const moveY = (dy / distance) * this.speed;
          super.move(moveX, moveY, 1);
        }
      }
    } else {
      this.behavior = BEHAVIOR.FOLLOW;
      this.followPlayer();
    }
  }
  
  // 寻找最近的敌人
  // 寻找最近的敌人
findNearestEnemy() {
  try {
    // 1. 检查enemies数组是否存在且不为空
    if (!databus.enemies || !Array.isArray(databus.enemies) || databus.enemies.length === 0) {
      return null;
    }

    // 2. 过滤出存活的敌人，并检查是否为空
    const aliveEnemies = databus.enemies.filter(e => e && !e.isDying);
    if (aliveEnemies.length === 0) {
      return null;
    }

    // 3. 安全使用reduce，提供初始值
    return aliveEnemies.reduce((nearest, current) => {
      return this.getDistanceTo(current) < this.getDistanceTo(nearest) ? current : nearest;
    }, aliveEnemies[0]); // 使用第一个元素作为初始值

  } catch (error) {
    console.error('findNearestEnemy error:', error);
    return null;
  }
}

  // 跟随玩家
  followPlayer() {
    if (!databus.player) return;
    
    // 确保速度已设置
    this.speed = this.baseSpeed * this.speedModifier;
    
    // 计算与玩家的距离向量
    const dx = databus.player.x - this.x;
    const dy = databus.player.y - this.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    
    // 如果离玩家太远，向玩家移动
    if (distance > 100) {
      // 计算移动方向
      const moveX = (dx / distance) * this.speed;
      const moveY = (dy / distance) * this.speed;
      
      // 应用移动
      super.move(moveX, moveY, 1);
      
      // 更新朝向
      this.direction = moveX > 0 ? 'right' : 'left';
    }
  }

  // 计算与其他狮子的排斥力
  calculateRepulsion() {
    const repulsion = { x: 0, y: 0 };
    const minDistance = 80; // 最小保持距离
    const repulsionStrength = 2; // 排斥力强度
    
    try {
      // 检查自身位置是否有效
      if (isNaN(this.x) || isNaN(this.y)) {
        console.error('calculateRepulsion: 自身位置无效');
        return repulsion;
      }
      
      // 安全获取所有其他狮子
      const allLions = [];
      
      // 安全添加玩家
      if (databus.player && databus.player !== this && 
          !isNaN(databus.player.x) && !isNaN(databus.player.y)) {
        allLions.push(databus.player);
      }
      
      // 安全添加盟友
      if (databus.allies && Array.isArray(databus.allies)) {
        databus.allies.forEach(lion => {
          if (lion && lion !== this && 
              !isNaN(lion.x) && !isNaN(lion.y)) {
            allLions.push(lion);
          }
        });
      }
      
      // 计算排斥力
      for (const lion of allLions) {
        const dx = this.x - lion.x;
        const dy = this.y - lion.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        // 防止除以零错误
        if (distance <= 0) {
          continue;
        }
        
        // 当距离小于最小距离时，产生排斥力
        if (distance < minDistance) {
          const force = (minDistance - distance) / minDistance * repulsionStrength;
          repulsion.x += (dx / distance) * force;
          repulsion.y += (dy / distance) * force;
        }
      }
      
      // 限制排斥力大小，防止过大值
      const maxForce = 5;
      repulsion.x = Math.max(-maxForce, Math.min(maxForce, repulsion.x));
      repulsion.y = Math.max(-maxForce, Math.min(maxForce, repulsion.y));
      
    } catch (error) {
      console.error('calculateRepulsion错误:', error);
    }
    
    return repulsion;
  }

  // 防御行为
  defend() {
    // 简单实现：原地不动攻击范围内的敌人
    this.attackEnemies();
  }

  // 攻击敌人
  attackEnemies() {
    if (++this.attackTimer >= this.attackInterval) {
      this.attackTimer = 0;
      
      // 寻找攻击范围内的敌人
      const targets = databus.enemies.filter(enemy => 
        !enemy.isDying && this.getDistanceTo(enemy) <= this.attackRange
      );
      
      if (targets.length > 0) {
        // 攻击最近的敌人
        const nearestEnemy = targets.reduce((nearest, current) => 
          this.getDistanceTo(current) < this.getDistanceTo(nearest) ? current : nearest
        );
        
        // 朝向敌人
        this.direction = nearestEnemy.x < this.x ? 'left' : 'right';
        
        // 造成伤害，传递自身作为攻击者
        nearestEnemy.takeDamage(this.attack, this);
        
        console.log(`Ally attacked enemy for ${this.attack} damage`);
      }
    }
  }

  // 设置行为模式
  setBehavior(newBehavior) {
    this.behavior = newBehavior;
  }
}